

`define DISPLAY_POINT	32'd10


module frag_clk(

    frag_clk,
    ad_data_vld,

    sample_fire,
    sample_done,

    cfg_sample_cnt,

    clk_sys,
    rst_n

    );


output frag_clk;
input ad_data_vld;

input sample_fire;
input sample_done;

input [31:0] cfg_sample_cnt;

input clk_sys;
input rst_n;


reg [31:0] sample_length;
always @ (posedge clk_sys)
    sample_length <= cfg_sample_cnt;


reg sample_now;
always @ (posedge clk_sys or negedge rst_n)
begin
if (rst_n == 1'b0)
    sample_now <= 1'b0;
else
    begin
    if (sample_done)
		sample_now <= 1'b0;
    else
        if (sample_fire)
		  sample_now <= 1'b1;
	end
end


reg [31:0] cnt_d_sample;
wire [31:0] cnt_d_sample_next;
assign cnt_d_sample_next = cnt_d_sample + `DISPLAY_POINT;

wire overflow_cnt_sample;
assign overflow_cnt_sample = (cnt_d_sample >= sample_length) ? 1'b1 : 1'b0;

always @ (posedge clk_sys or negedge rst_n)
begin
if (rst_n == 1'b0)
	cnt_d_sample <= 32'h0;
else
    begin
    if (sample_fire)
        cnt_d_sample <= `DISPLAY_POINT;
    else
        begin
        if (sample_now)
            begin
            if (overflow_cnt_sample)
                cnt_d_sample <= ad_data_vld ? cnt_d_sample_next - sample_length : cnt_d_sample;
            else
                cnt_d_sample <= ad_data_vld ? cnt_d_sample_next : cnt_d_sample;
            end
        else
            cnt_d_sample <= 32'h0;
        end
    end
end


wire frag_clk;
assign frag_clk = overflow_cnt_sample;



endmodule

